import React, { useState, useRef } from 'react';
import { ProTable } from '@ant-design/pro-table';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import {
  Space,
  Tag,
  Card,
  Table,
  Select,
  message,
  Button,
  Popconfirm,
} from 'antd';
import {
  PlusOutlined,
  MinusOutlined,
  EditOutlined,
  UserAddOutlined,
} from '@ant-design/icons';
import CardBreadcrumb from '@/components/CardBreadcrumb';

import { getInstitutionalusers } from '@/services/userManagement';
import OperationDetails from './modle/operationDetails'; //表格操作详情
import AddUserManage from './modle/addUserManage'; // 新增用户管理
import DelUserManage from './modle/delUserManage'; // 删除
import EnableOrDisable from './modle/EnableOrDisable'; // 删除
import ResetPassword from './modle/resetPassword'; // 密码重置
import RoleAuthorization from './modle/RoleAuthorization'; // 角色授权

import style from './index.less';
type GithubIssueItem = {
  url: string;
  id: number;
  number: number;
  title: string;
  state: string;
  comments: number;
  created_at: string;
  updated_at: string;
  closed_at?: string;
  kehuhao?: number;
  chinaName: string;
  englishName: string;
  customerStatus: any;
  shnehe: string;
  qudaoStatus: string;
  tel: string;
  hezuofnag: string;
  updataTime: string;
  updataPeople: string;
  createTime: string;
  createPeople: string;
};

const data1: any = [
  {
    key: 1,
    name: 'John Brown',
    age: 32,
    address: 'New York No. 1 Lake Park',
    tags: ['nice', 'developer'],
  },
  {
    key: 2,
    name: 'Jim Green',
    age: 42,
    address: 'London No. 1 Lake Park',
    tags: ['loser'],
  },
  {
    key: 3,
    name: 'Joe Black',
    age: 322,
    address: 'Sidney No. 1 Lake Park',
    tags: ['cool', 'teacher'],
  },
];

const CustomerUserManage: React.FC = (props) => {
  const [tableData, setTableData] = useState([]);
  const [isModalOpen, setIsModalOpen] = useState(false); // 表格操作详情弹窗
  const [isAddlOpen, setIsAddlOpen] = useState(false); //  新增弹窗
  const [tableRecord, setTableRecord] = useState({}); //  表格操作详情弹窗数据
  const [tableSelectedRows, setTableSelectedRows] = useState(); //  点击修改时表格数据
  const [tableSelectedKey, setTableSelectedKey] = useState([]); //  点击修改时表格数据
  const [addOrExit, setAddOrExit] = useState(''); //  新增/修改
  const [isdelOpen, setIsdelOpen] = useState(false); //删除弹窗
  const [enableDisable, setEnableDisable] = useState(false); //删除弹窗
  const [restPassword, setRestPassword] = useState(false); //重置密码
  const [roleAuthor, setRoleAuthor] = useState(false); //角色授权

  const selectRef = useRef();
  const actionRef = useRef<ActionType>();

  const columns1: ProColumns<GithubIssueItem>[] = [
    {
      title: '功能',
      dataIndex: 'caozuo ',
      hideInSearch: true,
      render: (text, record) => {
        return (
          <Button
            type="link"
            onClick={() => {
              setIsModalOpen(true);
              setTableRecord(record); // 给弹窗传递数据
            }}
          >
            详情
          </Button>
        );
      },
    },
    {
      title: '登录名',
      dataIndex: 'loginName',
      hideInSearch: true,
    },
    {
      title: '姓名',
      dataIndex: 'name',
      hideInSearch: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInSearch: true,
    },
    {
      title: '类型',
      dataIndex: 'type',
      hideInSearch: true,
    },
    {
      title: '所属机构',
      dataIndex: 'AffiliatedOrganie',
      hideInSearch: true,
    },
    {
      title: '角色',
      dataIndex: 'roles',
      hideInSearch: true,
    },
    {
      title: '密码状态',
      dataIndex: 'passwordStatus',
      hideInSearch: true,
      renderText: (text) => {
        return text === '1' ? (
          <span style={{ color: '#1890ff' }}> 已更改</span>
        ) : (
          '初始化'
        );
      },
    },

    {
      title: '更新时间',
      dataIndex: 'updataTime',
      hideInSearch: true,
    },

    {
      title: '创建时间',
      dataIndex: 'createTime',
      hideInSearch: true,
    },
    {
      title: '创建人',
      dataIndex: 'createPeople',
      hideInSearch: true,
    },
  ];

  // 表格格式
  const columnsform = [
    {
      title: '客户号',
      dataIndex: 'name',
      key: 'name',
      render: (text) => <a>{text}</a>,
    },
    {
      title: '中文名称',
      dataIndex: 'age',
      key: 'age',
    },
    {
      title: '英文名称',
      dataIndex: 'address',
      key: 'address',
    },
    {
      title: '客户类型',
      key: 'tags',
      dataIndex: 'tags',
      render: (_, { tags }) => (
        <>
          {tags.map((tag) => {
            let color = tag.length > 5 ? 'geekblue' : 'green';
            if (tag === 'loser') {
              color = 'volcano';
            }
            return (
              <Tag color={color} key={tag}>
                {tag.toUpperCase()}
              </Tag>
            );
          })}
        </>
      ),
    },
  ];

  const searchFormColumn = [
    {
      title: '登录名',
      key: 'loginName',
      dataIndex: 'loginName',
      hideInTable: true,
    },
    {
      title: '姓名',
      key: 'name',
      dataIndex: 'name',
      hideInTable: true,
    },
    {
      title: '所属机构',
      key: 'AffiliatedOrganie',
      dataIndex: 'AffiliatedOrganie',
      hideInTable: true,
      fieldProps: {
        showSearch: true,
      },
      renderFormItem: (_, { defaultRender, fieldProps, ...rest }, from) => {
        return (
          <Select
            ref={selectRef}
            {...fieldProps}
            key="AffiliatedOrganieSelect"
            onSearch={(value) => {
              if (value == 1) {
                setTableData(data1);
              } else {
                setTableData([]);
              }
            }}
            dropdownMatchSelectWidth={false}
            dropdownClassName={style.selectdropdownplatform}
            dropdownRender={() => (
              <Table
                style={{ padding: '10px' }}
                columns={columnsform}
                rowKey={(columns) => {
                  return columns.key;
                }}
                onRow={(record) => {
                  return {
                    onClick: (event) => {
                      from.setFieldsValue({
                        AffiliatedOrganie: record.key,
                      });
                      selectRef?.current?.blur();
                    }, // 点击行
                  };
                }}
                dataSource={tableData}
              />
            )}
          />
        );
      },
    },
  ];

  // 卡片头部面包屑
  const getBreadcrumbNavigation = () => {
    return <CardBreadcrumb props={props} />;
  };

  // 表格详情弹窗
  const showTableModal = () => {
    setIsModalOpen(true);
  };

  const handleTableOk = () => {
    setIsModalOpen(false);
  };

  const handleTableCancel = () => {
    setIsModalOpen(false);
  };

  // 判断选择的数据是否是一个或者多个，只能选择一个

  function JudgmentData(tableSelectedKey: any) {
    if (tableSelectedKey && tableSelectedKey.length > 1) {
      message.error('只能选取一个数据');
      return false;
    } else if (!tableSelectedKey || tableSelectedKey.length === 0) {
      message.warn('请选择一个数据');
      return false;
    } else {
      return true;
    }
  }

  return (
    <Card
      className={style.cardStyle}
      title={getBreadcrumbNavigation()}
      extra={
        <>
          <Space className={style.cardButton}>
            <Button
              type="link"
              icon={<PlusOutlined />}
              onClick={() => {
                setIsAddlOpen(true);
                setAddOrExit('add');
              }}
            >
              新增
            </Button>
            <Button
              type="link"
              onClick={() => {
                if (tableSelectedKey && tableSelectedKey.length > 1) {
                  message.error('只能选取一个数据');
                  return;
                } else if (!tableSelectedKey || tableSelectedKey.length === 0) {
                  message.warn('请选择一个数据');
                  return;
                }
                setAddOrExit('exit');
                setIsAddlOpen(true);
              }}
              icon={<EditOutlined />}
            >
              编辑
            </Button>
            <Button
              type="link"
              onClick={() => {
                const data = JudgmentData(tableSelectedKey);
                if (!data) {
                  return;
                }
                setIsdelOpen(true);
              }}
              icon={<MinusOutlined />}
            >
              删除
            </Button>
            <Button
              type="link"
              onClick={() => {
                const data = JudgmentData(tableSelectedKey);
                if (!data) {
                  return;
                }
                setEnableDisable(true);
              }}
              icon={<EditOutlined />}
            >
              启用/停用
            </Button>

            <Popconfirm
              placement="bottomRight"
              title="您确定要重置该用户密码"
              onConfirm={(value) => {
                const data = JudgmentData(tableSelectedKey);
                if (!data) {
                  return;
                }
                setRestPassword(true);
              }}
              okText="是"
              cancelText="否"
            >
              <Button type="link" icon={<EditOutlined />}>
                重置密码
              </Button>
            </Popconfirm>

            <Button
              type="link"
              onClick={() => {
                const data = JudgmentData(tableSelectedKey);
                if (!data) {
                  return;
                }
                setRoleAuthor(true);
              }}
              icon={<UserAddOutlined />}
            >
              授权角色
            </Button>
          </Space>
        </>
      }
      style={{ width: '100%' }}
    >
      <ProTable
        style={{ height: '100%' }}
        scroll={{ x: 1000 }}
        columns={[...columns1, ...searchFormColumn]}
        actionRef={actionRef}
        cardBordered
        form={{ labelWrap: true }}
        request={async (params: any = {}, sort: any, filter: any) => {
          const { data: response } = await getInstitutionalusers(params);
          return {
            data: response,
          };
        }}
        search={{
          labelWidth: 90,
        }}
        options={false} // 控制table设置按钮开关
        pagination={{
          showSizeChanger: true, // 显示页码切换的10/20/50
        }}
        editable={{
          type: 'multiple',
        }}
        defaultSize="small"
        rowSelection={{
          defaultSelectedRowKeys: [],

          onChange: (selectedRowKeys: any, selectedRowData: any) => {
            setTableSelectedRows(selectedRowData);
            setTableSelectedKey(selectedRowKeys);
          },
        }}
        tableAlertRender={({
          selectedRowKeys,
          selectedRows,
          onCleanSelected,
        }) => {
          return (
            <Space size={24}>
              <span>
                已选 {selectedRowKeys.length} 项
                <a style={{ marginInlineStart: 8 }} onClick={onCleanSelected}>
                  取消选择
                </a>
              </span>
            </Space>
          );
        }}
      />

      <OperationDetails // 表格详情弹窗
        tableRecord={tableRecord} //弹窗数据
        showModal={showTableModal}
        handleOk={handleTableOk}
        handleCancel={handleTableCancel}
        isModalOpen={isModalOpen}
      />

      <AddUserManage // 增加，编辑弹窗
        setIsModalOpen={setIsAddlOpen}
        isModalOpen={isAddlOpen}
        addOrExit={addOrExit}
        tableSelectedRows={tableSelectedRows}
      />
      <DelUserManage // 增加，编辑弹窗
        setIsModalOpen={setIsdelOpen}
        isModalOpen={isdelOpen}
        tableSelectedRows={tableSelectedRows}
      />
      <EnableOrDisable
        isModalOpen={enableDisable}
        tableSelectedRows={tableSelectedRows}
        setIsModalOpen={setEnableDisable}
      />
      <ResetPassword // 重置密码
        isModalOpen={restPassword}
        tableSelectedRows={tableSelectedRows}
        setIsModalOpen={setRestPassword}
      />
      <RoleAuthorization // 角色授权
        isModalOpen={roleAuthor}
        tableSelectedRows={tableSelectedRows}
        setIsModalOpen={setRoleAuthor}
      />
    </Card>
  );
};

export default CustomerUserManage;
